package com.example.controller;

import com.auth0.jwt.JWT;
import com.example.config.CommonConstant;
import com.example.config.shiro.JwtToken;
import com.example.enity.Admin;
import com.example.service.AdminService;
import com.example.util.JwtUtil;
import com.example.util.Md5;
import com.example.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisUtil redisUtil;

   @RequestMapping("/login")
   @ResponseBody
    public String login(String username,String pwd){
       Subject subject = SecurityUtils.getSubject();
       Admin admin = adminService.getAdminByUsername(username);
       if(admin == null){
           return "error";
       }
       String password = Md5.md5(pwd,admin.getSalt());
       if(password.equals(admin.getPwd())) {
           //用加密过后的密码生成token
           String token = JwtUtil.sign(username,password);
           //每次都会生成新的token
           JwtToken jwtToken = new JwtToken(token);
           //将token保存到redis中
           redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
           //redis中的过期时间是JwtToken过期时间的两倍
           redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
           return token;
       }else {
           return "error";
       }
   }

    @RequestMapping("/test")
    @ResponseBody
    public String test(String username,String pwd){
      return "test";
    }

}
